package com.enqualcomm.kids.activities;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.base.MyHandler;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.mvp.register.RegisterPagerAdapter;
import com.enqualcomm.kids.mvp.resetpassword.ResetPwdStep1Pager;
import com.enqualcomm.kids.mvp.resetpassword.ResetPwdStep2Pager;
import com.enqualcomm.kids.mvp.resetpassword.ResetPwdStep3Pager;
import com.enqualcomm.kids.mvp.resetpassword.ResetPwdStep4Pager;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.GetValidCodeForResetParams;
import com.enqualcomm.kids.network.socket.request.ResetPwdParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.view.BasePager;
import com.enqualcomm.kids.view.MyViewPager2;

import java.util.ArrayList;
import java.util.List;

import common.utils.PromptUtil;

public class GetMessageActivity extends BaseActivity implements View.OnClickListener {


    private View root_view;
    private MyViewPager2 mViewPager;
    private TextView title_bar_name;
    private ResetPwdParams resetPwdParams;
    private RegisterPagerAdapter adapter;
    /**
     * 有些页面得联网完成才跳转，需要防止多次点击,-1表示没有正在加载的页面
     *
     * 点击注册时，需要联网3次，loadingPage == -1 还没有注册， -2 注册成功没有登录， -3 登陆成功没有获取设备列表
     */
    private int loadingPage;
    private List<BasePager> pages;
    NetworkModel networkModel;
    public static final int START_COUNT = 1;
    int lasttime;
    boolean isShowSoftInput;


    MyHandler validcodeHandler = new MyHandler(this);

    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case START_COUNT:
                if (--lasttime >= 0) {
                    ((ResetPwdStep2Pager) pages.get(1)).refreshLasttime(lasttime);
                    validcodeHandler.sendEmptyMessageDelayed(START_COUNT, 1000);
                } else {
                    lasttime = 120;
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_message);

        networkModel = new NetworkModel();
        initView();
        initData();
        loadingPage = -1;
        lasttime = 120;
    }

    private void initData() {
        ResetPwdStep1Pager step1Pager = (ResetPwdStep1Pager) pages.get(0);
        Intent intent = getIntent();
        String extra = intent.getStringExtra("phoneNumber");
        if (!TextUtils.isEmpty(extra)) {
            step1Pager.setUsername(extra);
        }

        countryName = intent.getStringExtra("countryName");
        countryCode = intent.getStringExtra("countryCode");
        if (countryCode!=null){
            step1Pager.onCountryChooded(countryName,countryCode);
        }
    }

    private void initView() {
        //初始化title
        findViewById(R.id.title_bar_left_iv).setOnClickListener(this);
//        title_bar_name = (TextView) findViewById(R.id.title_bar_title_tv);
        title_bar_name = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
        View title_bar_terminal_icon_iv = findViewById(R.id.title_bar_terminal_icon_iv);
        title_bar_terminal_icon_iv.setVisibility(View.GONE);
        title_bar_name.setVisibility(View.VISIBLE);
        title_bar_name.setText(getString(R.string.get_password));

        mViewPager = (MyViewPager2) findViewById(R.id.pager);
        pages = new ArrayList<>();
        pages.add(new ResetPwdStep1Pager(this));
        adapter = new RegisterPagerAdapter(pages);
        mViewPager.setAdapter(adapter);

//        root_view = findViewById(R.id.root);
//        root_view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                int heightDiff = root_view.getRootView().getHeight() - root_view.getHeight();
//                if (heightDiff > 100) { // 如果高度差超过100像素，就很有可能是有软键盘...
//                    if (isShowSoftInput) {
//                        return;
//                    }
//                    root_view.setPadding(0, 0, 0, 0);
//
//                    isShowSoftInput = true;
//                } else {
//                    if (!isShowSoftInput) {
//                        return;
//                    }
//                    root_view.setPadding(0, 0, 0, DensityUtil.dip2px(RegisterActivity.this, 20));
//
//                    isShowSoftInput = false;
//                }
//            }
//        });
    }


    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        validcodeHandler.removeMessages(START_COUNT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_left_iv:
                int currentPage = mViewPager.getCurrentItem();
                if (currentPage==0) {
                    finish();
                }else if (currentPage==3) {
                    // 如果重置密码完成，点回退需要到登陆界面，并输入账号密码
                    Intent data = new Intent();
                    data.putExtra("username", resetPwdParams.getUsername());
                    data.putExtra("password", resetPwdParams.getUserpwd());
                    data.putExtra("countryName",countryName);
                    data.putExtra("countryCode",countryCode);
                    setResult(1, data);
                    finish();
                }else {
                    if (loadingPage!=-1) {
                        return;//还在处理下一步点击事件中，不让点击后退，避免发生异常
                    }

                    //清除页面的数据
                    validcodeHandler.removeMessages(START_COUNT);
                    lasttime = 120;
                    for (int i = 0; i < pages.size(); i++) {
                        pages.get(i).clear();
                    }

                    //后退回第一步
                    mViewPager.setCurrentItem(0);
                    title_bar_name.setText(getString(R.string.get_password));
                }
                break;
            default:
                break;
        }
    }

    public void nextPage(int nextPage,String inputStr){
        if (loadingPage == nextPage) {
            return;
        }
        switch (nextPage) {
            case 1://账号输入完成，开始输入验证码
                String[] split = inputStr.split(":");

                resetPwdParams = new ResetPwdParams();
                resetPwdParams.setUsername(split[0]);
                resetPwdParams.setCountry(split[1]);
                //应该确定发送验证码完成之后，再跳转
                loadingPage = 1;
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(new GetValidCodeForResetParams(split[0],split[1]), new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        loadingPage = -1;
                        PromptUtil.toast(getApplicationContext(),R.string.app_no_connection);
                        ((ResetPwdStep1Pager) pages.get(0)).setBtnEnable(true);
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        loadingPage = -1;
                        if (response.code == 0){
                            if (pages.size()<2) {
                                pages.add(new ResetPwdStep2Pager(GetMessageActivity.this));
                                adapter.notifyDataSetChanged();
                            }
                            ((ResetPwdStep2Pager) pages.get(1)).setUsername(resetPwdParams.getUsername());

                            mViewPager.setCurrentItem(1);
                            title_bar_name.setText(getString(R.string.input_validcode));

                            //定时刷新
                            validcodeHandler.sendEmptyMessage(START_COUNT);
                        }else {
                            ((ResetPwdStep1Pager) pages.get(0)).resetView();
                            PromptUtil.toast(getApplicationContext(),R.string.phonenumber_not_exist);
                        }

                    }
                }));
                break;
            case 2://验证码输入完成，开始输入密码
                validcodeHandler.removeMessages(START_COUNT);
                resetPwdParams.setValidcode(inputStr);
                if (pages.size()<3) {
                    pages.add(new ResetPwdStep3Pager(this));
                    adapter.notifyDataSetChanged();
                }

                mViewPager.setCurrentItem(2);
                title_bar_name.setText(getString(R.string.reset_new_pwd));
                break;
            case 3://密码输入完成，发送重置请求
                resetPwdParams.setUserpwd(inputStr);
                loadingPage = 3;
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(resetPwdParams, new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        loadingPage = -1;
                        PromptUtil.toast(getApplicationContext(),R.string.app_no_connection);
                        ((ResetPwdStep3Pager) pages.get(2)).setBtnEnable(true);
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        loadingPage = -1;
                        if (response.code==0){
                            //重置成功
                            AppDefault appDefault = new AppDefault();
                            appDefault.setUsername(resetPwdParams.getUsername());
                            appDefault.setPassword(resetPwdParams.getUserpwd());
                            appDefault.setCountry(resetPwdParams.getCountry());

                            ResetPwdStep4Pager registerStep4Pager = new ResetPwdStep4Pager(GetMessageActivity.this);
                            registerStep4Pager.setData(null,resetPwdParams.getUsername(),resetPwdParams.getUserpwd());

                            pages.add(registerStep4Pager);
                            adapter.notifyDataSetChanged();
                            mViewPager.setCurrentItem(3);
                            title_bar_name.setText(getString(R.string.reset_pwd_success));
                        }else if (response.code==6){
                            PromptUtil.toast(getApplicationContext(),R.string.validcode_wrong);
                        }
                    }
                }));
                break;
            case 4:
                //重置完成
                setResult(100);
                finish();
                break;
        }
    }


    private String countryCode;
    private String countryName;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==10000&&resultCode ==10001){
            countryCode = data.getStringExtra("number");
            countryName = data.getStringExtra("name");
            ((ResetPwdStep1Pager)pages.get(0)).onCountryChooded(countryName,countryCode);
        }
    }


    /**
     * 重新获取验证码
     */
    public void getValidCodeAgain() {
        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(new GetValidCodeForResetParams(resetPwdParams.getUsername(), resetPwdParams.getCountry()),
                new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        validcodeHandler.sendEmptyMessage(START_COUNT);
                    }
                }));
    }

}
